package com.zqh.web.interceptor;


import cn.hutool.json.JSONObject;
import com.zqh.web.common.login.LoginUser;
import com.zqh.web.common.login.LoginUserHolder;
import com.zqh.web.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Configuration
public class AuthenticationInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("access-token");

        // 检验token
        JSONObject claims = JwtUtil.parseToken(token);
        // 保存到ThreadLocal中
        Long userId = claims.get("userId",Long.class);
        String userName = claims.get("userName",String.class);
        String userRole = claims.get("userRole",String.class);
        LoginUserHolder.setLoginUser(new LoginUser(userId,userName,userRole));

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserHolder.clear();
    }


}
